<?php

class Article extends Zend_Db_Table_Row_Abstract
{
    protected $table;

    public function getTable() {
	if(is_null($this->table)) {
	    require_once 'ArticleTable.php';
	    $this->table = new ArticleTable();
	}
	return $this->table;
    }

    public function save(array $data) {
	$table = $this->getTable();
	$fields = $table->info(Zend_Db_Table_Abstract::COLS);

	foreach($data as $field => $value) {
	    if(!in_array($field, $fields)) {
		unset($data[$field]);
	    }
	}

	return $table->insert($data);
    }

    public function getLatestArticle($numberArticle) {
	$table = $this->getTable();
	$select = $table->select()->order('ts_creation DESC')->limit($numberArticle, 0);

	return $table->fetchAll($select);
    }

    public function getArticle($id_article) {
	$table = $this->getTable();
	$select = $table->select()->setIntegrityCheck(false)
			->from(array('a' => 'hermes_article'))
			->join(array('e' => 'hermes_event'),
				     'a.id_event = e.id_event',
			       array('nom_event', 'event_creation' => 'e.ts_creation'))
			->where('a.id_article = ?', $id_article);
			
	return $table->fetchRow($select);
    }

    public function getArticleWhereEventIs($id_event) {
	$table = $this->getTable();
	$select = $table->select()
			->order('ts_creation DESC')
			->where('id_event = ?', $id_event);

	return $table->fetchAll($select);
    }

    public function searchArticle($search) {
	$table = $this->getTable();
	
	$select = $table->select()
			->order('ts_creation DESC')
			->where('titre LIKE ?', '%' . $search . '%')
			->orWhere('corps LIKE ?', '%' . $search . '%');

	return $table->fetchAll($select);
    }
}
